<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="请选择类型" clearable>
            <el-option v-for="item in typeList" :key="item" :label="item" :value="item" @keyup.enter="handleQuery" />
          </el-select>
        </el-form-item>
        <el-form-item label="关键字查询" prop="filterText">
          <el-input v-model="filterText" placeholder="请输入关键字" clearable
        /></el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" />
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="filteredDeptList"
      row-key="id"
      :default-expand-all="isExpandAll"
      :row-class-name="highlightRowClass"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="type" label="类型" />
      <el-table-column prop="leader" label="负责人" />
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="scope">
          <span>{{ proxy.parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="success" icon="Plus" @click="handleAdd(scope.row)">新增</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="deptRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="归属上级" prop="parentId">
              <el-tree-select
                style="width: 100%"
                v-model="form.parentId"
                :data="deptOptions"
                :props="{ value: 'id', label: 'name', children: 'children' }"
                value-key="id"
                placeholder="选择归属上级"
                check-strictly
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="!form.parentId">
            <el-form-item label="类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择类型" clearable>
                <el-option v-for="item in typeList" :key="item" :label="item" :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="display: none">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leader">
              <el-input v-model="form.leader" placeholder="请输入负责人" maxlength="20" />
            </el-form-item>
          </el-col>
          <el-col :span="12" style="display: none">
            <el-form-item label="联系电话" prop="phone">
              <el-input v-model="form.phone" placeholder="请输入联系电话" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12" style="display: none">
            <el-form-item label="等级" prop="grade">
              <el-input v-model="form.grade" placeholder="请输入" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, getCurrentInstance, nextTick, computed } from "vue"
import { ElForm } from "element-plus"
// import { parseTime } from "@/utils/ruoyi.js"
import { listDept, getDept, delDept, addDept, updateDept, listDeptExcludeChild } from "@/api/org/dept"
import type { DeptForm, QueryParams } from "@/api/org/types"

defineOptions({
  name: "OrgList"
})
const { proxy }: any = getCurrentInstance()!

const deptList = ref<any[]>([])
const deptList1 = ref<any[]>([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const title = ref("")
const deptOptions = ref<any[]>([])
const isExpandAll = ref(false)
const refreshTable = ref(true)
const queryRef = ref<InstanceType<typeof ElForm>>()
const deptRef = ref<InstanceType<typeof ElForm>>()
const typeList = ref<any>(["财务", "运营", "客服", "其他"])
const form = ref<DeptForm>({
  id: undefined,
  parentId: undefined,
  name: undefined,
  orderNum: 0,
  leader: undefined,
  phone: undefined,
  grade: undefined,
  type: undefined,
  status: "0"
})

const queryParams = ref<QueryParams>({
  name: undefined,
  status: undefined
})

const rules = ref({
  parentId: [{ required: true, message: "归属上级不能为空", trigger: "blur" }],
  type: [{ required: true, message: "类型不能为空", trigger: "blur" }],
  name: [{ required: true, message: "名称不能为空", trigger: "blur" }]
})

const getList = () => {
  loading.value = true
  listDept(queryParams.value).then((response: any) => {
    deptList.value = proxy!.handleTree(response.data.teamList, "id")
    deptList1.value = proxy!.handleTree(response.data.teamList, "id")
    loading.value = false
  })
}

const cancel = () => {
  open.value = false
  reset()
}

const reset = () => {
  form.value = {
    id: undefined,
    parentId: undefined,
    name: undefined,
    orderNum: 0,
    leader: undefined,
    phone: undefined,
    grade: undefined,
    status: "0"
  }
  deptRef.value?.resetFields()
}

const handleQuery = () => {
  getList()
}

const resetQuery = () => {
  queryRef.value?.resetFields()
  filterText.value = ""
  handleQuery()
}

const handleAdd = (row?: any) => {
  reset()
  console.log(row)
  if (row?.id) {
    listDept({}).then((response: any) => {
      deptOptions.value = proxy!.handleTree(response.data.teamList, "id")
    })
    form.value.parentId = row.id
  } else {
    deptOptions.value = proxy!.handleTree(
      [{ id: 0, name: "无(顶级层级，选择'无'默认生成一级目录)", children: [] }],
      "id"
    )
  }
  open.value = true
  title.value = "添加"
}

const toggleExpandAll = () => {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

const handleUpdate = (row: any) => {
  reset()
  listDeptExcludeChild(row.id).then((response: any) => {
    if (row.parentId == 0) {
      deptOptions.value = proxy!.handleTree(
        [...response.data, { id: 0, name: "无(顶级层级，选择'无'默认生成一级目录)", children: [] }],
        "id"
      )
    } else {
      deptOptions.value = proxy!.handleTree(response.data, "id")
    }
  })
  getDept(row.id).then((response: any) => {
    form.value = response.data
    open.value = true
    title.value = "修改"
  })
}

const submitForm = () => {
  deptRef.value?.validate((valid: any) => {
    if (valid) {
      if (form.value.id) {
        updateDept(form.value).then(() => {
          proxy!.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addDept(form.value).then(() => {
          proxy!.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}
// 过滤后的数据
const filterText = ref("")
const filteredDeptList = computed(() => {
  if (!filterText.value) {
    return deptList.value.map((node) => {
      const newNode = { ...node }
      newNode.highlight = false
      if (newNode.children) {
        newNode.children = newNode.children.map((child: any) => ({ ...child, highlight: false }))
      }
      return newNode
    })
  }
  return filterTree(deptList.value, filterText.value)
})

const filterTree = (nodes: any[], keyword: string): any[] => {
  return nodes
    .map((node) => ({ ...node }))
    .filter((node) => {
      const matches = node.name?.includes(keyword) || node.type?.includes(keyword) || node.leader?.includes(keyword)
      node.highlight = matches && keyword.length > 0
      if (node.children && node.children.length) {
        node.children = filterTree(node.children, keyword)
        const hasHighlightedChild = node.children.some(
          (child: any) => child.highlight || (child.children && child.children.length > 0)
        )
        return matches || hasHighlightedChild
      }
      return matches
    })
}

const highlightRowClass = ({ row }: { row: any }) => {
  return row.highlight ? "highlight-row" : ""
}
const handleDelete = (row: any) => {
  proxy!.$modal
    .confirm(`是否确认删除名称为"${row.name}"的数据项?`)
    .then(() => delDept(row.id))
    .then(() => {
      getList()
      proxy!.$modal.msgSuccess("删除成功")
    })
    .catch(() => {})
}

getList()
</script>
<style lang="scss" scoped>
:deep(.highlight-row) {
  background-color: #fff3e0 !important; /* 高亮背景色，例如浅橙色 */
  font-weight: bold; /* 可选：加粗文字 */
}
</style>
